﻿using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CallCenter.Data;
using CallCenter.Data.BizUtilities;
using System.Configuration;
using System.Data;
using CallCenter.Security;
using CallCenter.Data.Models;
using CallCenter.Data.Misc;
//using iTextSharp.text.pdf;
//using iTextSharp.text;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web.Caching;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Web.UI.WebControls;
using CallCenter.Data.Helper;
using System.Collections;
//using;

namespace CallCenter.Web.Controllers
{
    public class ProductRequestGridController : BaseController
    {
        // GET: ProductRequestGrid
        private static string _conn;
        DB dbConn;
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ProductRequestHistory()
        {
            ProductRequestViewModel cmpy = new ProductRequestViewModel();
            return View(cmpy);
        }

        [HttpPost]
        public JsonResult CreateProductRequest(ProductRequestViewModel model)
        {
           
            int userId = this.Bridge.AccountUtility.GetUserIDByUserNames(User.Identity.Name.ToLower());
            model.UserId = userId;

            var returnMessage = this.Bridge.ProductRequestUtility.InsertToProductRequest(model);
            if (!returnMessage.Status)
                ModelState.AddModelError("Error", returnMessage.Message);
            else
            {
                return Json(new AjaxSuccess { Message = "Success" }, JsonRequestBehavior.AllowGet);
            }
            //  }
            return Json(returnMessage, JsonRequestBehavior.AllowGet);
            // return Json(new AjaxFailure { Errors = ModelState.SerializeErrors }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetCompanyProject(ProductRequestViewModel model, int id)
        {
                
            var companyprojects = this.Bridge.ProductRequestUtility.GetCompanyProject(id);

            return Json(companyprojects, JsonRequestBehavior.AllowGet);

        }
        public JsonResult GetProducts(ProductViewModel model)
        {
            var products = this.Bridge.ProductRequestUtility.GetProduts();

            return Json(products, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetDepartments(DepartmentViewModel model)
        {
            var dept = this.Bridge.ProductRequestUtility.GetDepartments();
            return Json(dept, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetProjectManagers(EmployeeAuthViewModel model)
        {
            var projmanager = this.Bridge.ProductRequestUtility.GetProjectManagers();
            return Json(projmanager, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetLeadDevelopers(EmployeeAuthViewModel model)
        {
            var leaddev = this.Bridge.ProductRequestUtility.GetLeadDevelopers();
            return Json(leaddev, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetHeldEmployee(EmployeeAuthViewModel model)
        {
            var empl = this.Bridge.ProductRequestUtility.GetHeldByContacts();
            return Json(empl, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdateProductRequest(ProductRequestViewModel model)
        {
         
            int userId = this.Bridge.AccountUtility.GetUserIDByUserNames(User.Identity.Name.ToLower());
            model.UserId = userId;

            var returnMessage = this.Bridge.ProductRequestUtility.UpdateToProductRequest(model);
            if (!returnMessage.Status)
                ModelState.AddModelError("Error", returnMessage.Message);
            else
            {
                return Json(new AjaxSuccess { Message = "Success" }, JsonRequestBehavior.AllowGet);
            }
         
            return Json(returnMessage, JsonRequestBehavior.AllowGet);
          
        }

        [HttpPost]
        public JsonResult DeleteProject(ProductRequestViewModel model)
        {
            //delete items into respective tables
            int id = model.id;
            this.Bridge.ProductRequestUtility.Delete(id);
            var returnMessage = "Success";
            return Json(returnMessage, JsonRequestBehavior.AllowGet);

        }

        public JsonResult GetInvlouedEmployees(InvoluedEmployeeVM model)
        {
            var InvoEmp = this.Bridge.ProductRequestUtility.GetInvoluedEmployees();
            return Json(InvoEmp, JsonRequestBehavior.AllowGet);
        }

        public JsonResult PaidBy(PaidByViewModel model)
        {
            var paidby = this.Bridge.ProductRequestUtility.PaidBy();
            return Json(paidby, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetAllProjectHistory()
        {
            ProductRequestViewModel cmpy = new ProductRequestViewModel();
            return View(cmpy);
        }
       
       
        public JsonResult GetAllProjects()
        {
            var Proj = this.Bridge.ProductRequestUtility.GetAllProjects();
            return Json(Proj, JsonRequestBehavior.AllowGet);
        }

        #region Report
        [HttpPost]
        public ActionResult generatePdf(int productRequestId)
        {

            string filepath = "";
            string fileName = "";
            string baseUrl = "";
            ProductRequestViewModel model = new ProductRequestViewModel();
            model.id = productRequestId;
            DataRow dr = this.Bridge.ProductRequestUtility.GetAllPDF(model.id);
            if (dr == null)
            {
                return null;
            }
            else
            {
                #region get data for header
                string project = dr["project"].ToString();

                string clientCompany = dr["clientCompany"].ToString();
                string StreetOne = dr["streetOne"].ToString();
                string StreetTwo = dr["streetTwo"].ToString();
                string city = dr["city"].ToString();
                string zip = dr["zip"].ToString();
                string state = dr["state"].ToString();

                //Nullable<DateTime> TempStartDate = DateTime.Parse(dr["startDate"].ToString());
                //string startDate = TempStartDate.Value.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                //Nullable<DateTime> TempEndDate = DateTime.Parse(dr["expectedDeliveryDate"].ToString());
                //string endDate = TempEndDate.Value.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                string leadDeveloperName = dr["leadDeveloperName"].ToString();
                string projectManagerName = dr["projectManagerName"].ToString();
                #endregion

                #region defining font
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                BaseFont tFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1257, false);
                BaseFont valFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1257, false);
                Font timesTitle = new Font(bfTimes, 18, Font.BOLD, BaseColor.BLACK);
                Font times = new Font(bfTimes, 14, Font.BOLD, BaseColor.BLACK);
                Font header = new Font(tFont, 13, Font.NORMAL, BaseColor.BLACK);
                Font valueFont = new Font(valFont, 11, Font.NORMAL, BaseColor.BLACK);
                Font georgia = FontFactory.GetFont("georgia", 12f);
                #endregion

                #region defining pdf path and property
                var pdf = new Document();
                string path = Server.MapPath("../");
                DirectoryInfo di = null;

                try
                {

                    if (!Directory.Exists(path + "Reports\\" + clientCompany))

                        di = Directory.CreateDirectory(path + "Reports\\" + clientCompany);

                    filepath = path + "Reports\\" + clientCompany + "\\" + project + clientCompany + productRequestId + ".pdf";
                    fileName = "Reports/" + clientCompany + "/" + project + clientCompany + productRequestId + ".pdf";
                    if (System.IO.File.Exists(filepath))
                    {
                        System.IO.File.Delete(filepath);
                        //if (Cache["List"] != null)
                        //    Cache["List"] = null;
                    }
                    iTextSharp.text.pdf.PdfWriter.GetInstance(pdf, new System.IO.FileStream(filepath, FileMode.Create));
                    pdf.Open();
                    pdf.SetMargins(100, 100, 120, 120);
                #endregion

                    #region pdf header for report

                    PdfPCell headerEmptyRow = new PdfPCell(new Phrase(""));
                    headerEmptyRow.Colspan = 3;
                    headerEmptyRow.BorderWidth = 0;

                    PdfPCell emptyCell = new PdfPCell(new Phrase(" "));
                    emptyCell.BorderWidth = 0;

                    PdfPTable headerTable = new PdfPTable(3); //create table with 3 column
                    headerTable.WidthPercentage = 100f;

                    PdfPCell PSRCell = new PdfPCell(new Phrase("Project Status Report\n", timesTitle));
                    PSRCell.Colspan = 3;
                    PSRCell.HorizontalAlignment = 1;
                    PSRCell.BorderWidth = 0;

                    PdfPCell PNameCell = new PdfPCell(new Phrase("Project Name: " + project + "\n\n", times));
                    PNameCell.Colspan = 3;
                    PNameCell.HorizontalAlignment = 1;
                    PNameCell.BorderWidth = 0;

                    PdfPCell coAdCl = new PdfPCell(new Phrase("Resource Navigation, Inc.\n26 Fox Road \nWaltham, MA 02451"));
                    coAdCl.BorderWidth = 0;

                    PdfPCell clientComp = new PdfPCell(new Phrase("Company (client) \n", times));
                    clientComp.BorderWidth = 0;
                    clientComp.Colspan = 2;

                    PdfPCell PMCell = new PdfPCell(new Phrase("Project Manager \n" + projectManagerName));
                    PMCell.BorderWidth = 0;
                    PMCell.HorizontalAlignment = 2;

                    PdfPCell PMName = new PdfPCell(new Phrase(projectManagerName));
                    PMName.BorderWidth = 0;

                    PdfPCell LDCell = new PdfPCell(new Phrase("Lead Developer\n" + leadDeveloperName));
                    LDCell.BorderWidth = 0;
                    LDCell.HorizontalAlignment = 2;

                    PdfPCell LDName = new PdfPCell(new Phrase(leadDeveloperName));
                    LDName.BorderWidth = 0;

                    PdfPCell clientInfo = new PdfPCell(new Phrase(clientCompany + "\n" + StreetOne + "\n" + StreetTwo + "\n" + city + " " + state + ", " + zip));
                    clientInfo.BorderWidth = 0;
                    clientInfo.Colspan = 2;

                    //PdfPCell dateCell = new PdfPCell(new Phrase("Start Date: " + startDate + "\nEnd Date: " + endDate));
                    //dateCell.HorizontalAlignment = 2;
                    //dateCell.BorderWidth = 0;

                    headerTable.AddCell(PSRCell);
                    headerTable.AddCell(PNameCell);
                    headerTable.AddCell(coAdCl);
                    headerTable.AddCell(emptyCell);
                  //  headerTable.AddCell(dateCell);
                    headerTable.AddCell(headerEmptyRow);
                    headerTable.AddCell(headerEmptyRow);
                    headerTable.AddCell(clientComp);
                    headerTable.AddCell(PMCell);
                    headerTable.AddCell(clientInfo);
                    headerTable.AddCell(LDCell);

                    pdf.Add(headerTable);
                    #endregion


                    DataTable dtList = this.Bridge.TaskUtility.PdfTask(productRequestId);


                    if (dtList.Rows.Count > 0)
                    {
                        #region body table for project task

                        PdfPTable bodyTable = new PdfPTable(new float[] { 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f });
                        bodyTable.WidthPercentage = 100f;
                        PdfPCell taskNameHead = new PdfPCell(new Phrase("Task", times));

                        PdfPCell taskDescriptionHead = new PdfPCell(new Phrase("Description", times));
                        taskDescriptionHead.Colspan = 2;
                        PdfPCell startDateHead = new PdfPCell(new Phrase("Start Date", times));
                        PdfPCell endDataHead = new PdfPCell(new Phrase("End Date", times));

                        PdfPCell statusHead = new PdfPCell(new Phrase("Status", times));

                        PdfPCell budgetHead = new PdfPCell(new Phrase("Budget", times));
                        PdfPCell heldByHead = new PdfPCell(new Phrase("Held By", times));
                        PdfPCell gapHead = new PdfPCell(new Phrase("Gap", times));



                        bodyTable.AddCell(taskNameHead);
                        bodyTable.AddCell(taskDescriptionHead);
                        bodyTable.AddCell(startDateHead);
                        bodyTable.AddCell(endDataHead);
                        bodyTable.AddCell(statusHead);
                        bodyTable.AddCell(budgetHead);
                        bodyTable.AddCell(heldByHead);
                        bodyTable.AddCell(gapHead);

                        pdf.Add(bodyTable);
                        #endregion

                        #region import data for task list

                        int rowCount = dtList.Rows.Count;

                        for (int i = 0; i < rowCount; i++)
                        {
                            PdfPTable listTable = new PdfPTable(new float[] { 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f });
                            listTable.WidthPercentage = 100f;
                            var row = dtList.Rows[i];

                            string tName = row["taskName"].ToString();
                            string description = row["description"].ToString();

                            DateTime TempSDate = DateTime.Parse(row["startDate"].ToString());
                            string sDate = TempSDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));

                            DateTime TempEDate = DateTime.Parse(row["endDate"].ToString());
                            string eDate = TempEDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                            string status = row["status"].ToString();
                            int budget = Convert.ToInt16(row["Budget"]);
                            string heldContactName = row["heldByName"].ToString();
                            int gap = Convert.ToInt16(row["gap"]);




                            listTable.AddCell(tName);
                            PdfPCell descCell = new PdfPCell(new Phrase(description));
                            descCell.Colspan = 2;
                            listTable.AddCell(descCell);
                            listTable.AddCell(sDate);
                            listTable.AddCell(eDate);
                            listTable.AddCell(status);
                            listTable.AddCell(budget.ToString());
                            listTable.AddCell(heldContactName);
                            listTable.AddCell(gap.ToString());
                            pdf.Add(listTable);
                        }



                        #endregion
                    }
                    else
                    {

                        #region body table for project task

                        PdfPTable bodyTable = new PdfPTable(new float[] { 10f });
                        bodyTable.WidthPercentage = 100f;
                        PdfPCell taskNameHead = new PdfPCell(new Phrase("No Task Found", times));
                        taskNameHead.HorizontalAlignment = Element.ALIGN_CENTER;
                        taskNameHead.VerticalAlignment = Element.ALIGN_CENTER;
                       



                        bodyTable.AddCell(taskNameHead);
                      

                        pdf.Add(bodyTable);
                        #endregion
                    }

                }
                catch (Exception ex)
                {
                    fileName = ex.ToString();
                }

                finally
                {

                    pdf.Close();
                    baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"].ToString();

                }
                //pdf.Close();
                //baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"].ToString();
                return Json(baseUrl + fileName, JsonRequestBehavior.AllowGet);
                //  return json(filepath;
            }
        }
        #endregion

        #region SendReport
       
        public string GetContactsViewToSendReport(int productRequestId, int CompanyId)
        {
            _conn = ConfigurationManager.ConnectionStrings["mainConnection"].ToString();
            dbConn = new DB(_conn);
            Hashtable ht = new Hashtable();
            ht.Add("productRequestId", productRequestId);
            ht.Add("CompanyId", CompanyId);
            DataSet HDDList = dbConn.GetDataSetForSP("Sp_GetAllEmployeeByProductIDandCompanyID", ht);
            List<EmployeeMailVM> EmployeeMailVMList = new List<EmployeeMailVM>();

            EmployeeMailVMList.AddRange(HDDList.Tables[0].AsEnumerable().Select(dataRow =>
                new EmployeeMailVM
                {
                    email = dataRow.Field<string>("email"),
                    firstName = dataRow.Field<string>("firstName"),
                    lastName = dataRow.Field<string>("lastName"),
                    Role = "ProjectLead"
                }).ToList());

            EmployeeMailVMList.AddRange(HDDList.Tables[1].AsEnumerable().Select(dataRow =>
               new EmployeeMailVM
               {
                   email = dataRow.Field<string>("email"),
                   firstName = dataRow.Field<string>("firstName"),
                   lastName = dataRow.Field<string>("lastName"),
                   Role = "InvolvedEmployee"
               }).ToList());

            EmployeeMailVMList.AddRange(HDDList.Tables[2].AsEnumerable().Select(dataRow =>
               new EmployeeMailVM
               {
                   email = dataRow.Field<string>("email"),
                   firstName = dataRow.Field<string>("firstName"),
                   lastName = dataRow.Field<string>("lastName"),
                   Role = "Companycontact"
               }).ToList());
            ViewBag.ProductRequestId = productRequestId;
            ViewBag.CompanyId = CompanyId;
            return RenderRazorViewToString("~/Views/ProductRequestGrid/_EmailPartialView.cshtml", EmployeeMailVMList);
        }
        #endregion

        #region   Report View

        public string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                         viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                             ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }
        #endregion

        #region ReportByMail
      
        public string SendReportBySelectedMail(int productRequestId, int CompanyId, string SelectedMail)
        {
            try
            {
                DataRow dr = this.Bridge.ProductRequestUtility.GetAllPDF(productRequestId);
                string subject = "Project Request Report";
                string filePath = Server.MapPath("~/Template/ProductReportTemplate.html");

                string content = System.IO.File.ReadAllText(filePath);
                DataTable dtList = this.Bridge.TaskUtility.PdfTask(productRequestId);
                //string TableContent = "";
                //if (dtList.Rows.Count > 0)
                //{
                //    TableContent += "<table class='TableDetail' style='width: 95%; float: left; border: 1px solid; margin: 10px; float: left;'>";
                //    for (int i = 0; i < dtList.Rows.Count; i++)
                //    {
                //        TableContent += "<tr class='HeaderTable'>";
                //        PdfPTable listTable = new PdfPTable(6);
                //        listTable.WidthPercentage = 200f;
                //        var row = dtList.Rows[i];
                //        string tName = row["taskName"].ToString();
                //        string description = row["description"].ToString();
                //        DateTime TempSDate = DateTime.Parse(row["startDate"].ToString());
                //        string sDate = TempSDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                //        DateTime TempEDate = DateTime.Parse(row["endDate"].ToString());
                //        string eDate = TempEDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                //        string status = row["status"].ToString();
                //        int gap = Convert.ToInt16(row["gap"]);
                //        int budget = Convert.ToInt16(row["Budget"]);
                //        string heldContactName = row["heldByName"].ToString();

                //        TableContent += "<td style='border: 1px solid;>" + tName + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + description + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + sDate + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + eDate + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + status + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + gap + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + budget + "</td>";
                //        TableContent += "<td style='border: 1px solid;>" + heldContactName + "</td>";
                //        TableContent += "</tr>";
                //    }
                //    TableContent += "</table>";
                //}
                //else
                //{
                //    TableContent += "No task found";
                //}

                //content = content.Replace("##TABLECONTENT##", TableContent);
                content = content.Replace("###LeadDeveloper###", dr["leadDeveloperName"].ToString());
                content = content.Replace("###ProjectManager###", dr["projectManagerName"].ToString());
                content = content.Replace("###Company###", dr["clientCompany"].ToString());
                content = content.Replace("###ProjectName###", dr["project"].ToString());

                string Body = content;
                string[] to = SelectedMail.Split('|').ToArray();
                string[] cc = { };
                WebMail.SendMail(to, cc, subject, Body, null);
                return "Success";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        #endregion
    }

    public class EmployeeMailVM
    {
        public string email { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string Role { get; set; }
    }
}

